package com.webridge.plm.listener;

import java.beans.PropertyVetoException;
import java.io.Serializable;
import java.rmi.RemoteException;

import org.apache.log4j.Logger;










import com.webridge.plm.util.PartUtil;

import wt.enterprise.EnterpriseHelper;
import wt.enterprise.RevisionControlled;
import wt.epm.EPMDocument;
import wt.events.KeyedEvent;
import wt.events.KeyedEventListener;
import wt.fc.PersistenceManagerEvent;
import wt.lifecycle.LifeCycleServiceEvent;
import wt.log4j.LogR;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.part.WTPartUsageLink;
import wt.pom.TransactionListener;
import wt.services.ServiceEventListenerAdapter;
import wt.services.StandardManager;
import wt.session.SessionServerHelper;
import wt.type.TypedUtilityServiceHelper;
import wt.util.WTException;
import wt.vc.VersionControlHelper;
import wt.vc.VersionControlServiceEvent;
import wt.vc.wip.WorkInProgressServiceEvent;

public class LPartPostStoreServiceListener extends StandardManager implements LPartPostStoreService,Serializable{
	
	/** */
    private static final long serialVersionUID = 1L;
    private static Logger logger = LogR.getLogger(LPartPostStoreServiceListener.class.getName());
	private static final String CLASSNAME = LPartPostStoreServiceListener.class.getName();
	private KeyedEventListener listener;
	
	@Override
	public String getConceptualClassname() {
		return CLASSNAME;
	}
	
	public static LPartPostStoreServiceListener newLPartPostStoreServiceListener()
			throws WTException {
	    LPartPostStoreServiceListener listenerService = new LPartPostStoreServiceListener();
		listenerService.initialize();
		return listenerService;
	}
	
	class LPartPostStoreService extends ServiceEventListenerAdapter {
		public LPartPostStoreService(String managerName) {
			super(managerName);
		}

		public void notifyVetoableEvent(Object event) throws WTException, PropertyVetoException {
			if (!(event instanceof KeyedEvent)) {
				return;
			}
			KeyedEvent keyedEvent = (KeyedEvent) event;
			logger.debug("LPartPostStoreServiceListener keyedEvent==>"
					+ keyedEvent.getEventType()+",TARGET:" + keyedEvent.getEventTarget());
			String eventType = keyedEvent.getEventType();
			Object target = keyedEvent.getEventTarget();
            if (eventType.equals("POST_STORE")) {

                if (target instanceof WTPart) {
                    WTPart part = (WTPart) target;
                    debugMethod(part,eventType);
                }
            } else if (eventType.equals("POST_MODIFY")) {
                if (target instanceof WTPart) {
                    WTPart part = (WTPart) target;
                    part = (WTPart) VersionControlHelper.getLatestIteration(part);
                    debugMethod(part,eventType);

                }else if(target instanceof WTPartUsageLink){
                    WTPartUsageLink link = (WTPartUsageLink) target;
                    logger.debug("PartUsageLink add new:" + link.getRoleBObject());
                }
            } else if (eventType.equals("STATE_CHANGE")) {
                if (target instanceof WTPart) {
                    WTPart part = (WTPart) target;
                    part = (WTPart) VersionControlHelper.getLatestIteration(part);

                    debugMethod(part,eventType);

                }
            }else if (eventType.equals("NEW_VERSION")) {
                if (target instanceof WTPart) {
                    WTPart part = (WTPart) target;
                    part = (WTPart) VersionControlHelper.getLatestIteration(part);
                    debugMethod(part,eventType);

                }
            }else if (eventType.equals("POST_CHECKIN")) {
                if (target instanceof WTPart) {
                    WTPart part = (WTPart) target;
                    part = (WTPart) VersionControlHelper.getLatestIteration(part);
                    debugMethod(part,eventType);
                }
            }
		}
	}
	public static void debugMethod(WTPart part,String eventType) throws WTException{
	     boolean flag = SessionServerHelper.manager.setAccessEnforced(false);

         try {
             String type = TypedUtilityServiceHelper.service.getExternalTypeIdentifier(part);

             logger.debug("type target==>" + type);
             if (type != null && type.indexOf("com.lenovo.LPart") > -1) {
                 // Call interface.
                 String state = part.getState().getState().toString();
                 String version = part.getVersionIdentifier().getValue() + "."
                         + part.getIterationIdentifier().getValue();
                 logger.debug(eventType+ " LPart listener..." + part.getNumber() + ",State:" + state + ",Version:"
                         + version);
                 WTPartMaster pm = part.getMaster();
                 WTPart latestPart = PartUtil.getLatestPartByMaster(pm);
                 String lstate = latestPart.getState().getState().toString();
                 String lversion = latestPart.getVersionIdentifier().getValue() + "." + part.getIterationIdentifier().getValue();
                 logger.debug(eventType + " latestPart ..." + latestPart.getNumber() + ",lState:" + lstate + ",lVersion:"
                         + lversion+",source:" + latestPart.getSource().getStringValue());
             }

         } catch (RemoteException e) {
             e.printStackTrace();
         } finally {
             SessionServerHelper.manager.setAccessEnforced(flag);
         }
	}
	protected void performStartupProcess() {
		listener = new LPartPostStoreService(this.getConceptualClassname());
        getManagerService().addEventListener(listener,PersistenceManagerEvent.generateEventKey(PersistenceManagerEvent.POST_STORE));
        getManagerService().addEventListener(listener, PersistenceManagerEvent.generateEventKey("POST_MODIFY"));// 修改之后
        getManagerService().addEventListener(listener, PersistenceManagerEvent.generateEventKey("PRE_STORE"));// 新建
        getManagerService().addEventListener(listener, WorkInProgressServiceEvent.generateEventKey("POST_CHECKIN"));// 检入后
        getManagerService().addEventListener(listener, VersionControlServiceEvent.generateEventKey(VersionControlServiceEvent.NEW_VERSION));
        getManagerService().addEventListener(listener, LifeCycleServiceEvent.generateEventKey(LifeCycleServiceEvent.STATE_CHANGE));

	}

}
